package ssi.tools;

import java.sql.SQLException;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;

import ssi.tools.Connector;

public class Tool {

	public static boolean remindPassword(String email) {
		Connector con;
		try {
			   con=new Connector();
			   String alphabet = "123456789abcdefghijklmnoprstuwyz";
			   Random r = new Random();
			   String helpPassword = ""; 
			   for (int i = 0; i < 10; i++) {
				   helpPassword += alphabet.charAt(r.nextInt(alphabet.length()));
			   }
			   
			con.getStatement().executeUpdate("UPDATE `users` SET `password` = \""+DigestUtils.md5Hex(helpPassword)+"\" where email = \""+email+"\"");
			new SendEmail().sendPasswordEmail(email, helpPassword);
			con.closeConnection();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}
	
	
	private static byte PESEL[] = new byte[11];

	public static boolean checkPeselFormat(String pesel) {
		if (pesel.length() != 11) {
			return false;
		} else {
			for (int i = 0; i < 11; i++) {
				PESEL[i] = Byte.parseByte(pesel.substring(i, i + 1));
			}
			if (checkSum()) {
				return true;
			} else {
				return false;
			}
		}

	}

	private static boolean checkSum() {
		int sum = 1 * PESEL[0] + 3 * PESEL[1] + 7 * PESEL[2] + 9 * PESEL[3] + 1
				* PESEL[4] + 3 * PESEL[5] + 7 * PESEL[6] + 9 * PESEL[7] + 1
				* PESEL[8] + 3 * PESEL[9];
		sum %= 10;
		sum = 10 - sum;
		sum %= 10;

		if (sum == PESEL[10]) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean checkEmailFormat(String email){
		 String emailRegex= "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
		 boolean check=email.matches(emailRegex);
		 if(check){
			 return true;
		 }else{
			 return false;
		 }
	}
}
